package com.netcracker.ui.command;

import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.UserService;
import com.netcracker.entity.Right;
import com.netcracker.entity.record.UserRecord;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.WrongUserException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class RegistrationCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RegistrationCommand.class);
    private final ServiceFacade serviceFacade;
    
    public RegistrationCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String date = request.getParameter("bDate");
            String fullName = request.getParameter("fullName");
            Integer countryID = Integer.parseInt(request.getParameter("countryID"));
            UserService userService = serviceFacade.getUserService();
            try {
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); 
                Date regDate = null;
                Date bDate = null;
                try {
                    regDate = formatter.parse((new Date()).toString());
                    bDate = formatter.parse(date);
                } catch (ParseException ex) {
                    LOGGER.error(ex.getMessage(), ex);
                }
                UserRecord userRecord = new UserRecord();
                userRecord.setCountry(countryID);
                userRecord.setRegisterDate(regDate);
                userRecord.setDateOfBirth(bDate);
                userRecord.setFullName(fullName);
                userRecord.setLogin(username);
                userRecord.setPasswordHash(password);
                userRecord.setRight(Right.USER);
                try {
                    userService.registerUser(userRecord);
                    LOGGER.info("User registered: ", username);
                    request.setAttribute("success", "Регистрация прошла успешно. Используйте свои данные для входа на сайт.");
                } catch (WrongUserException ex) {
                    LOGGER.error(ex.getMessage(), ex);
                    request.setAttribute("error", ex.getMessage());
                } catch (DataTransmittingException ex) {
                    request.setAttribute("error", "Ошибка обращения к БД.");
                    LOGGER.error("DB error:", ex);
                }
            } catch (NoSuchAlgorithmException ex) {
                LOGGER.error(ex.getMessage(), ex);
                request.setAttribute("error", "Произошла ошибка при регистрации. Повторите попытку позже.");
            } 
        return "index.jsp";
        
    }
    
}